import threading

from django.template.loader import render_to_string
from .IpInfo import ip_protect
from django.core.mail import send_mail, mail_admins
from MyBlog.settings import EMAIL_HOST_USER


def send_email_async(from_visitor, to_visitor, article, comment_id):
    threading.Thread(target=send_email,
                     args=(from_visitor, to_visitor, article, comment_id)).start()


def send_email(from_visitor, to_visitor, article, comment_id):
    subject = '大鹌鹑的博客新回复'
    to = to_visitor.email

    to_visitor_name = to_visitor.nickname + ip_protect(to_visitor.ip_address) + '[' + to_visitor.city + ']'
    from_visitor_name = from_visitor.nickname + ip_protect(from_visitor.ip_address) + '[' + from_visitor.city + ']'
    text = '%s，您好。%s在文章《%s》中回复了您，点击下方按钮查看。' % (
        to_visitor_name, from_visitor_name, article.title)
    aritcle_link = 'http://127.0.0.1:8000/article/%d/#%d' % (article.id, comment_id)

    html_content = render_to_string('xBlog/mail.html', {'content': text, 'link': aritcle_link})

    send_mail(subject, text, '大鹌鹑 <' + EMAIL_HOST_USER + '>', [to], fail_silently=True, html_message=html_content)

    mail_admins('邮件提醒已发送', '邮件提醒已经成功发送给%s' % to_visitor_name, fail_silently=True)
